//constants
var subscription = null;
var modelArray = new Array();
var models = null;
var xmlDoc1 = null;
var mdmservicedn = null;
var modelName = null;
var systemURL = jQuery("#systemurl").val();
var userName = jQuery("#user").val();
var password = jQuery("#password").val();
var authenticationRequest= "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Header/><SOAP:Body><Authenticate xmlns=\"http://schemas.cordys.com/1.0/webgateway\"><username>" + userName + "</username><password>" + password + "</password></Authenticate></SOAP:Body></SOAP:Envelope>";

	var getOrganizationCollectionRequest = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Body><GetCollection xmlns=\"http://schemas.cordys.com/1.0/xmlstore\"><folder xmlns=\"http://schemas.cordys.com/1.0/xmlstore\" recursive=\"true\" detail=\"true\" version=\"organization\">/Cordys/mdm/publishedmodels</folder></GetCollection></SOAP:Body></SOAP:Envelope>";

	var getISVCollectionRequest = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Body><GetCollection xmlns=\"http://schemas.cordys.com/1.0/xmlstore\"><folder xmlns=\"http://schemas.cordys.com/1.0/xmlstore\" recursive=\"true\" detail=\"true\" version=\"isv\">/Cordys/mdm/publishedmodels</folder></GetCollection></SOAP:Body></SOAP:Envelope>";

	var httpObject = null;
	var WSDL_PREFIX				= "wsdl:";
	var AUTH_GATEWAY = systemURL + "/com.eibus.web.soap.Authenticate.wcp"
	var WSDL_GATEWAY = systemURL + "/com.eibus.web.tools.wsdl.WSDLGateway.wcp";
	var GATEWAY = systemURL +"/cordys/com.eibus.web.soap.Gateway.wcp";
	//var ORGANIZATION = "organization=o=system,cn=cordys,cn=TR186,o=vanenburg.com";
	var ORGANIZATION = jQuery("#organization").val();
	var gatewayhttpURL = GATEWAY + "?" + ORGANIZATION;
	var authenticationhttpURL = AUTH_GATEWAY + "?" + ORGANIZATION;
	
	
function init() {
	if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(stateUpdated);
		wave.setParticipantCallback(participantUpdated);
		jQuery("#usernameRow").hide();
		jQuery("#passwordRow").hide();
	}
}
function getModels()
{
		systemURL = jQuery("#systemurl").val();
		userName = jQuery("#user").val();
		password = jQuery("#password").val();
		AUTH_GATEWAY = systemURL + "/com.eibus.web.soap.Authenticate.wcp"
		WSDL_GATEWAY = systemURL + "/com.eibus.web.tools.wsdl.WSDLGateway.wcp";
	    GATEWAY = systemURL +"/cordys/com.eibus.web.soap.Gateway.wcp";
	    ORGANIZATION = jQuery("#organization").val();
		gatewayhttpURL = GATEWAY + "?" + ORGANIZATION;
		authenticationhttpURL = AUTH_GATEWAY + "?" + ORGANIZATION;
		authenticationRequest= "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Header/><SOAP:Body><Authenticate xmlns=\"http://schemas.cordys.com/1.0/webgateway\"><username>" + userName + "</username><password>" + password + "</password></Authenticate></SOAP:Body></SOAP:Envelope>";
		responseDoc = getOrganizationModels();
		if(responseDoc == null)
			alert("No models found");
		else
		{
			fillModels(responseDoc);
		}	

}
function get(key) {
  var ret = null;
  if (wave) {
    ret = wave.getState().get(key); 
  }
  return ret;
}

function set(key, value) {
  var obj = {};
  obj[key] = value;
  if (wave) {
    wave.getState().submitDelta(obj);
  }  
}

function rm(key) {
  var obj = {};
  obj[key] = null;  
  if (wave) {
    wave.getState().submitDelta(obj);
  }  
}

function getViewerId() {
  var ret = null;
  if (wave) {
    ret = wave.getViewer().getDisplayName();
  }
  return ret;
}

 function hasExistingGame() {
  var ret = false;

  if (get(gameExists) != null) {
    ret = true;
  }

  return ret;
}

function participantUpdated()
{
	
}	

function stateUpdated()
{
	if(get('logExists') == "true")
	{
		jQuery("#logs").show();
		fillLogsTable();
	}	
	else 	jQuery("#logs").hide();
	
}

function fillLogsTable()
{
	jQuery(".logCol").remove();
	debugger;
	var logs = JSON.parse(get('LOGS'));
	for(var a =0; a < logs.length; a++)
	{
		var row = document.createElement("tr");
		row.setAttribute("class","logCol");
		for(var i = 0; i < 6; i++)
		{
			var column = document.createElement("td");
			var celltext = document.createTextNode(logs[a][i]);
			column.appendChild(celltext);
			row.appendChild(column);
		}	
		jQuery("#logs").append(row);
	}
}

function fillModels(responseDoc)
{
	models = responseDoc.getElementsByTagName("tuple");
	var selectBox = document.getElementById("selectModel");
	for(var a=selectBox.options.length-1;a>=1;a--)
	{
		selectBox.options[a] = null;
	}
	var value = null;
	for(var i =0; i < models.length; i++)
	{
		var model = models[i].getElementsByTagName("model");
		value = model[0].getAttribute("modelid");
		var optn = document.createElement("OPTION");
		optn.text = value;
		optn.value = value;
		selectBox.options.add(optn);
	}
}

function getOrganizationModels()
{
	var responseXMLDoc = null;
	try //Internet Explorer
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.load(file);
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.open("POST",authenticationhttpURL,false);
		xmlhttp.send(xmlDoc);
		responseXMLDoc =xmlhttp.responseXML;;

	}
	catch(e)
	{
		try //Firefox, Mozilla, Opera, etc.
		{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			var parser = new DOMParser();
			if(document.getElementById('chkAuth').checked )
			{
				xmlDoc1 = parser.parseFromString(authenticationRequest,"text/xml");
				var xmlhttp1 = new window.XMLHttpRequest();
				xmlhttp1.open("POST",authenticationhttpURL,false,userName,password);
				xmlhttp1.send(xmlDoc1.cloneNode(true));
				xmlDoc1 = xmlhttp1.responseXML.documentElement;
			}	
			xmlDoc=parser.parseFromString(getOrganizationCollectionRequest,"text/xml");
			var xmlhttp = new window.XMLHttpRequest();
			if(jQuery("#chkAuth").checked)
				gatewayhttpURL += ( (gatewayhttpURL.indexOf("?") < 0) ? "?" : "&") + "wcp-session=" + 	encodeURIComponent(xmlDoc1.textContent);
			xmlhttp.open("POST",gatewayhttpURL,false);
			xmlhttp.send(xmlDoc.cloneNode(true));
			responseXMLDoc = xmlhttp.responseXML;
		}
		catch(e)
		{
			try //Google Chrome
			{
				alert(e.message);
				debugger;
				var parser = new DOMParser();
				xmlDoc1 = parser.parseFromString(authenticationRequest,"text/xml");
				var xmlhttp1 = new window.XMLHttpRequest();
				xmlhttp1.open("POST",authenticationhttpURL,false);
				xmlhttp1.setRequestHeader("Content-Type", " text/xml; charset=UTF-8");
				xmlhttp1.send(authenticationRequest);
				xmlDoc1 = xmlhttp1.responseXML.documentElement;
				xmlDoc=parser.parseFromString(getOrganizationCollectionRequest,"text/xml");
				var xmlhttp = new window.XMLHttpRequest();
				gatewayhttpURL += ( (gatewayhttpURL.indexOf("?") < 0) ? "?" : "&") + "wcp-session=" + 	encodeURIComponent(xmlDoc1.textContent);
				xmlhttp.open("POST",gatewayhttpURL,false);
				xmlhttp.send(getOrganizationCollectionRequest);
			responseXMLDoc = xmlhttp.responseXML;
			}
			catch(e)
			{
				error=e.message;
				alert(error);
			}
		}
	}
	return responseXMLDoc;
}

function getSubscriptions()
{
	if(jQuery("#selectModel option:selected").text() == "---Select Model---")
		return;
		jQuery("#subscriptions").show();
		jQuery("#subscriptions").empty();
	for(var i =0; i < models.length; i++)
	{
		var model = models[i].getElementsByTagName("model");
		mdmservicedn = models[i].getElementsByTagName("mdmservicedn")[0].textContent;
		modelName = model[0].getAttribute("modelid");
		if(modelName == jQuery("#selectModel option:selected").text())
		{
			links = models[i].getElementsByTagName("link");
			for(var len = 0; len < links.length; len++)
			{
			    var subscriptionName = links[len].getElementsByTagName("sodtocod")[0].getAttribute("name")
				var row = document.createElement("tr");
				var column = document.createElement("td");
				var celltext = document.createTextNode(subscriptionName);
				column.appendChild(celltext);

				var column1 = document.createElement("td");
				var input = document.createElement("input");
				input.setAttribute('type','button');
				input.setAttribute('value','Upload');
				input.setAttribute('name',subscriptionName);
				input.setAttribute('mdmservicedn',mdmservicedn);
				input.setAttribute('onClick','upLoad(this)');
				column1.appendChild(input);

				row.appendChild(column);
				row.appendChild(column1);

				jQuery("#subscriptions").append(row);
				modelArray[subscriptionName] = links[len];
				var subscriptionName = links[len].getElementsByTagName("codtosod")[0].getAttribute("name")
				var row = document.createElement("tr");
				var column = document.createElement("td");
				var celltext = document.createTextNode(subscriptionName);
				column.appendChild(celltext);

				var column1 = document.createElement("td");
				var input = document.createElement("input");
				input.setAttribute('type','button');
				input.setAttribute('value','Download');
				input.setAttribute('name',subscriptionName);
				input.setAttribute('mdmservicedn',mdmservicedn);
				input.setAttribute('onClick','downLoad(event )');
				column1.appendChild(input);

				row.appendChild(column);
				row.appendChild(column1);

				jQuery("#subscriptions").append(row);
				modelArray[subscriptionName] = links[len];
			}
			break;
		}
	}
}
function upLoad(subscription)
{
	if( get('logExists') != true)
		set('logExists','true');
	var subscriptionName = subscription.name;
	var sodentity  = modelArray[subscriptionName].getElementsByTagName("sodentity")[0].textContent;
	var codentity  = modelArray[subscriptionName].getElementsByTagName("codentity")[0].textContent;
	var sod  = modelArray[subscriptionName].getElementsByTagName("sod")[0].textContent;
debugger;
	var uploadRequest = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  		+"<SOAP:Body>"
   	 +"<Upload xmlns=\"http://schemas.cordys.com/rcor/1.0\">"
      +"<codtype xmlns=\"http://schemas.cordys.com/rcor/1.0\">"
       +"<backend>"
        +"<entity/>"
         +"<evaluaterules>true</evaluaterules>"
          +"<stopsynchronization>false</stopsynchronization>"
           +"<stateflow>true</stateflow>"
           +"<threadparameters xml:space=\"preserve\">"
           +"<parameters></parameters>"
          +"</threadparameters>"
        +"</backend>"
      +"</codtype>"
    +"</Upload>"
  +"</SOAP:Body>"
+"</SOAP:Envelope>"
var parser = new DOMParser();
xmlDoc2 = parser.parseFromString(uploadRequest,"text/xml");
xmlDoc = xmlDoc2.cloneNode(true);
xmlDoc.getElementsByTagName("codtype")[0].setAttribute("name",codentity);
xmlDoc.getElementsByTagName("backend")[0].setAttribute("name",sod);
xmlDoc.getElementsByTagName("entity")[0].textContent = sodentity;
xmlDoc.getElementsByTagName("SOAP:Envelope")[0].setAttribute("reciever",mdmservicedn);

for(var i =0; i < models.length; i++)
	{
		var model = models[i].getElementsByTagName("model");
		value = model[0].getAttribute("modelid");
		if(value == jQuery("#selectModel option:selected").text())
		{
			var backend = models[i].getElementsByTagName("backends")[0];
			var backends = backend.getElementsByTagName("backend");
			for(var j =0; j < backends.length; j++)
			{
				var backendName = backends[j].getElementsByTagName("backend")[0].getElementsByTagName("identity")[0].textContent;
				if(backendName == sod)
				{
					var reqdDoc = backends[j].getElementsByTagName("threadparameters")[0].cloneNode(true);
					var replaceableNode = xmlDoc.getElementsByTagName("threadparameters")[0];
					var parentNode = replaceableNode.parentNode;
					parentNode.replaceChild(reqdDoc, replaceableNode);
				}
				break;
			}
		  break;
		 }
	}
	try{
	if(netscape)
		netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	var xmlhttp = new window.XMLHttpRequest();
	if(document.getElementById('chkAuth').checked )
		gatewayhttpURL += ( (gatewayhttpURL.indexOf("?") < 0) ? "?" : "&") + "wcp-session=" + 	encodeURIComponent(xmlDoc1.textContent);
	xmlhttp.open("POST",gatewayhttpURL,false);
	xmlhttp.send(xmlDoc.cloneNode(true));
	responseXMLDoc = xmlhttp.responseXML;
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	var timeValue = "" + ((hours >12) ? hours -12 :hours)
	if (timeValue == "0") timeValue = 12;
	timeValue += ((minutes < 10) ? ":0" : ":") + minutes
	timeValue += ((seconds < 10) ? ":0" : ":") + seconds
	timeValue += (hours >= 12) ? " P.M." : " A.M."
	updateLogs(responseXMLDoc,"Upload",timeValue);
	}
	catch(e)
	{
		alert(e.message);
	}
}

function updateLogs(responseXMLDoc,operation,timeValue)
{
	var logs = JSON.parse(get('LOGS'));
	if(logs == null)
	{
		logs = [];
	}
	
	var logObj = [];
	logObj[0] = modelName;
	logObj[1] = systemURL;
	logObj[2] = getViewerId();
	logObj[3] = operation;
	logObj[4] = timeValue;
	var processid = responseXMLDoc.getElementsByTagName("processid")[0].textContent;
	logObj[5] = processid;
	logs.push(logObj);
	
	set('LOGS', JSON.stringify(logs));
}

function showAuthentication()
{
	debugger;
	if(document.getElementById('chkAuth').checked )
	{
		jQuery("#usernameRow").show();
		jQuery("#passwordRow").show();
	}
	else
	{
		jQuery("#usernameRow").hide();
		jQuery("#passwordRow").hide();
	}
}


